#include					"AudioModule.h"
#include					"SoundPacket.h"

AudioModule::AudioModule()
{

}

AudioModule::~AudioModule()
{

}

void						AudioModule::init()
{
	_opMap[CHGVOL] = &AudioModule::chgvol;
	_opMap[AUDIOPACKET] = &AudioModule::audiopacket;
}

void						AudioModule::interpret(Packet * packet)
{
	ProtocolAudio *prot = packet->getData<ProtocolAudio>(1);
	if (prot != NULL)
	{
		if (_opMap.find(*prot) != _opMap.end())
			(this->*_opMap[*prot])(packet);
		else
			std::cout << "[CRITICAL] Can't find operator [" << (unsigned int) *prot << "] on AudioModule" <<  std::endl;
	}
	else
		std::cout << "[CRITICAL] Error on AudioModule" << std::endl;
	delete prot;
}

bool						AudioModule::chgvol(Packet *packet)
{
	unsigned int id = _api->network()->getId(packet->getFrom());

	if (id > 0)
	{
		byte *val = packet->getData<byte>(1);
		std::cout << "change volume called with vol " << (unsigned int) *val << " %" << std::endl;
		_api->audio()->setVolume((float) *val / 100.f);
		return true;
	}
	return false;
}

bool						AudioModule::audiopacket(Packet *packet)
{
	unsigned int id = _api->network()->getId(packet->getFrom());

	if (id > 0)
	{
	  SoundPacket			*audiopacket = _api->audio()->getPacket(id);
	  //	  audiopacket->setTime((unsigned int) (_api->time()->getTime() * 1000));
	  _api->audio()->decode(packet, audiopacket, id);
	  _api->audio()->packetReady(id);
	  return true;
	}
	return false;
}
